package Array;

public class 螺旋矩阵Ⅱ {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int i, j;
        int iMin = 0;
        int iMax = n - 1;
        int jMin = 0;
        int jMax = n - 1;
        int k = 1;
        while (k <= n * n) {
            i = iMin;
            j = jMin;
            while (j != jMax) {
                matrix[i][j++] = k++;
            }
            while (i != iMax) {
                matrix[i++][j] = k++;
            }
            while (j != jMin) {
                matrix[i][j--] = k++;
            }
            while (i != iMin) {
                matrix[i--][j] = k++;
            }
            if (iMin == iMax && jMin == jMax && k == n * n) {
                matrix[i][j] = k;
                break;
            }
            iMin++;
            jMin++;
            iMax--;
            jMax--;
        }
        return matrix;
    }
}
